<template>
  <div class="page-content">
    <ElForm :model="queryForm" :inline="true">
      <!-- 第一行：基础筛选 -->
      <ElRow :gutter="16" style="margin-bottom: 16px">
        <ElCol :xs="24" :sm="8" :md="6" :lg="16">
          <ElSpace :size="1">
            <ElFormItem label="关键字搜索">
              <ElInput
                v-model="queryForm.keyword"
                placeholder="用户openid/商品名称"
                clearable
                style="min-width: 200px"
              />
            </ElFormItem>
            <ElFormItem label="用户openid">
              <ElInput
                v-model="queryForm.openid"
                placeholder="请输入用户openid"
                clearable
                style="min-width: 180px"
              />
            </ElFormItem>
            <ElFormItem label="购物车状态">
              <ElSelect
                v-model="queryForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 100%; min-width: 150px"
              >
                <ElOption label="有效" value="active" />
                <ElOption label="无效" value="inactive" />
                <ElOption label="过期" value="expired" />
              </ElSelect>
            </ElFormItem>
          </ElSpace>
        </ElCol>

        <ElCol :xs="24" :sm="8" :md="12" :lg="8">
          <ElFormItem>
            <ElSpace :size="12">
              <ElButton type="primary" @click="handleSearch" v-ripple>搜索</ElButton>
              <ElButton @click="resetQuery" v-ripple>重置</ElButton>
              <ElButton type="info" @click="showStatsDialog" v-ripple>统计信息</ElButton>
            </ElSpace>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <ArtTable
      :data="cartList"
      :loading="loading"
      :total="pagination.total"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :show-pagination="true"
      :hide-on-single-page="false"
      index
    >
      <template #default>
        <ElTableColumn label="商品图片" prop="product.image" width="80">
          <template #default="scope">
            <ElImage
              v-if="scope.row.product?.image"
              :src="scope.row.product.image"
              style="width: 50px; height: 50px"
              fit="cover"
              :preview-src-list="[scope.row.product.image]"
            />
            <span v-else>-</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="用户信息" min-width="200">
          <template #default="scope">
            <div class="user-info">
              <div class="openid">{{ scope.row.openid }}</div>
              <div class="nickname" v-if="scope.row.userNickName">
                {{ scope.row.userNickName }}
              </div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="商品信息" min-width="200">
          <template #default="scope">
            <div class="product-info" v-if="scope.row.product">
              <div class="name">{{ scope.row.product.name }}</div>
              <div class="type">
                <ElTag :type="getProductTypeTagType(scope.row.product.type)" size="small">
                  {{ getProductTypeText(scope.row.product.type) }}
                </ElTag>
              </div>
            </div>
            <span v-else>商品信息缺失</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="单价" prop="price" width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.price) }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="数量" prop="quantity" width="80">
          <template #default="scope">
            {{ scope.row.quantity }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="总金额" width="120">
          <template #default="scope">
            {{ formatAmount(calculateTotalAmount(scope.row.price, scope.row.quantity)) }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="状态" prop="status" width="100">
          <template #default="scope">
            <ElTag :type="getCartStatusTagType(scope.row.status)">
              {{ getCartStatusText(scope.row.status) }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="商品状态" width="100">
          <template #default="scope">
            <ElTag
              v-if="scope.row.product"
              :type="getProductStatusTagType(scope.row.product.status)"
              size="small"
            >
              {{ getProductStatusText(scope.row.product.status) }}
            </ElTag>
            <span v-else>-</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="创建时间" prop="createTime" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </ElTableColumn>
        <ElTableColumn label="更新时间" prop="updateTime" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </ElTableColumn>
        <ElTableColumn fixed="right" label="操作" width="180">
          <template #default="scope">
            <ElButton type="primary" link @click="showDetailDialog(scope.row)">详情</ElButton>
            <ElButton type="info" link @click="viewUserCart(scope.row.openid)">
              查看用户购物车
            </ElButton>
          </template>
        </ElTableColumn>
      </template>
    </ArtTable>

    <!-- 购物车项详情弹窗 -->
    <ElDialog v-model="detailDialogVisible" title="购物车项详情" width="700px" align-center>
      <div v-if="currentCartItem" class="cart-detail">
        <ElDescriptions :column="2" border>
          <ElDescriptionsItem label="购物车ID">
            {{ currentCartItem._id }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="用户OpenID">
            {{ currentCartItem.openid }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="用户昵称" v-if="currentCartItem.userNickName">
            {{ currentCartItem.userNickName }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="商品ID">
            {{ currentCartItem.productId }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="数量">
            {{ currentCartItem.quantity }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="单价">
            {{ formatAmount(currentCartItem.price) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="总金额">
            {{
              formatAmount(calculateTotalAmount(currentCartItem.price, currentCartItem.quantity))
            }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="购物车状态">
            <ElTag :type="getCartStatusTagType(currentCartItem.status)">
              {{ getCartStatusText(currentCartItem.status) }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="创建时间">
            {{ formatDate(currentCartItem.createTime) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="更新时间">
            {{ formatDate(currentCartItem.updateTime) }}
          </ElDescriptionsItem>
        </ElDescriptions>

        <!-- 商品信息 -->
        <div class="mt-4" v-if="currentCartItem.product">
          <ElDescriptions :column="2" border title="关联商品信息">
            <ElDescriptionsItem label="商品名称">
              {{ currentCartItem.product.name }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="商品类型">
              <ElTag :type="getProductTypeTagType(currentCartItem.product.type)">
                {{ getProductTypeText(currentCartItem.product.type) }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="商品价格">
              {{ formatAmount(currentCartItem.product.price) }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="商品状态">
              <ElTag :type="getProductStatusTagType(currentCartItem.product.status)">
                {{ getProductStatusText(currentCartItem.product.status) }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="商品描述" span="2">
              {{ currentCartItem.product.description || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="商品图片" span="2">
              <ElImage
                v-if="currentCartItem.product.image"
                :src="currentCartItem.product.image"
                style="width: 100px; height: 100px"
                fit="cover"
                :preview-src-list="[currentCartItem.product.image]"
              />
              <span v-else>-</span>
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="detailDialogVisible = false">关闭</ElButton>
        </div>
      </template>
    </ElDialog>

    <!-- 用户购物车弹窗 -->
    <ElDialog v-model="userCartDialogVisible" title="用户购物车" width="800px" align-center>
      <div v-if="userCartItems.length > 0">
        <ElTable :data="userCartItems" size="small">
          <ElTableColumn label="商品图片" width="80">
            <template #default="scope">
              <ElImage
                v-if="scope.row.product?.image"
                :src="scope.row.product.image"
                style="width: 40px; height: 40px"
                fit="cover"
              />
              <span v-else>-</span>
            </template>
          </ElTableColumn>
          <ElTableColumn label="商品名称" prop="product.name" min-width="150" />
          <ElTableColumn label="商品类型" width="100">
            <template #default="scope">
              <ElTag
                v-if="scope.row.product"
                :type="getProductTypeTagType(scope.row.product.type)"
                size="small"
              >
                {{ getProductTypeText(scope.row.product.type) }}
              </ElTag>
            </template>
          </ElTableColumn>
          <ElTableColumn label="单价" width="100">
            <template #default="scope">
              {{ formatAmount(scope.row.price) }}
            </template>
          </ElTableColumn>
          <ElTableColumn label="数量" prop="quantity" width="80" />
          <ElTableColumn label="总金额" width="100">
            <template #default="scope">
              {{ formatAmount(calculateTotalAmount(scope.row.price, scope.row.quantity)) }}
            </template>
          </ElTableColumn>
          <ElTableColumn label="状态" width="100">
            <template #default="scope">
              <ElTag :type="getCartStatusTagType(scope.row.status)" size="small">
                {{ getCartStatusText(scope.row.status) }}
              </ElTag>
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
      <div v-else class="empty-cart">
        <ElEmpty description="该用户购物车为空" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="userCartDialogVisible = false">关闭</ElButton>
        </div>
      </template>
    </ElDialog>

    <!-- 统计信息弹窗 -->
    <ElDialog v-model="statsDialogVisible" title="购物车统计信息" width="600px" align-center>
      <div v-if="cartStats" class="stats-info">
        <ElRow :gutter="16">
          <ElCol :span="12">
            <ElStatistic title="总购物车项数" :value="cartStats.totalItems" />
          </ElCol>
          <ElCol :span="12">
            <ElStatistic title="有效购物车项" :value="cartStats.activeItems" />
          </ElCol>
        </ElRow>
        <ElRow :gutter="16" style="margin-top: 16px">
          <ElCol :span="12">
            <ElStatistic title="无效购物车项" :value="cartStats.inactiveItems" />
          </ElCol>
          <ElCol :span="12">
            <ElStatistic title="过期购物车项" :value="cartStats.expiredItems" />
          </ElCol>
        </ElRow>
        <ElRow :gutter="16" style="margin-top: 16px">
          <ElCol :span="12">
            <ElStatistic title="总商品数量" :value="cartStats.totalQuantity" />
          </ElCol>
          <ElCol :span="12">
            <ElStatistic
              title="总金额"
              :value="formatAmount(cartStats.totalAmount)"
              :precision="0"
            />
          </ElCol>
        </ElRow>
        <ElRow :gutter="16" style="margin-top: 16px">
          <ElCol :span="12">
            <ElStatistic title="用户数量" :value="cartStats.uniqueUsers" />
          </ElCol>
          <ElCol :span="12">
            <ElStatistic title="商品种类" :value="cartStats.uniqueProducts" />
          </ElCol>
        </ElRow>
        <ElRow :gutter="16" style="margin-top: 16px">
          <ElCol :span="12">
            <ElStatistic title="人均购物车项" :value="cartStats.avgItemsPerUser" />
          </ElCol>
          <ElCol :span="12">
            <ElStatistic title="平均每项数量" :value="cartStats.avgQuantityPerItem" />
          </ElCol>
        </ElRow>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="statsDialogVisible = false">关闭</ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage } from 'element-plus'
  import {
    CartService,
    type CartItem,
    type CartListParams,
    getCartStatusText,
    getCartStatusTagType,
    getProductTypeText,
    getProductTypeTagType,
    getProductStatusText,
    getProductStatusTagType,
    formatAmount,
    calculateTotalAmount,
    formatDate,
    calculateCartStats
  } from '@/api/cartApi'

  defineOptions({ name: 'CartManage' })

  // 响应式数据
  const loading = ref(false)
  const detailDialogVisible = ref(false)
  const userCartDialogVisible = ref(false)
  const statsDialogVisible = ref(false)
  const currentCartItem = ref<CartItem | null>(null)
  const userCartItems = ref<CartItem[]>([])
  const cartStats = ref<any>(null)

  // 查询表单
  const queryForm = reactive<CartListParams>({
    keyword: '',
    openid: '',
    status: undefined
  })

  // 分页数据
  const pagination = reactive({
    page: 1,
    size: 10,
    total: 0
  })

  // 购物车列表
  const cartList = ref<CartItem[]>([])

  // 获取购物车列表
  const getCartList = async () => {
    try {
      loading.value = true
      const params: CartListParams = {
        page: pagination.page,
        size: pagination.size,
        ...queryForm
      }
      const response = await CartService.getCartList(params)
      console.log('response', response)
      if (response.code === 200) {
        cartList.value = response.data
        pagination.total = response.total
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      ElMessage.error('获取购物车列表失败')
      console.error('获取购物车列表失败:', error)
      cartList.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    getCartList()
  }

  // 重置查询
  const resetQuery = () => {
    Object.assign(queryForm, {
      keyword: '',
      openid: '',
      status: undefined
    })
    pagination.page = 1
    getCartList()
  }

  // 分页处理
  const handleSizeChange = (val: number) => {
    pagination.size = val
    pagination.page = 1
    getCartList()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    getCartList()
  }

  // 显示购物车项详情
  const showDetailDialog = async (row: CartItem) => {
    try {
      const response = await CartService.getCartDetail(row._id!)
      console.log('detail response', response)
      currentCartItem.value = response.data
      detailDialogVisible.value = true
    } catch (error) {
      ElMessage.error('获取购物车详情失败')
      console.error('获取购物车详情失败:', error)
    }
  }

  // 查看用户购物车
  const viewUserCart = async (openid: string) => {
    try {
      const response = await CartService.getUserCart(openid)
      console.log('user cart response', response)
      if (response.code === 200) {
        userCartItems.value = response.data
        userCartDialogVisible.value = true
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      ElMessage.error('获取用户购物车失败')
      console.error('获取用户购物车失败:', error)
      userCartItems.value = []
    }
  }

  // 显示统计信息
  const showStatsDialog = () => {
    cartStats.value = calculateCartStats(cartList.value)
    statsDialogVisible.value = true
  }

  // 生命周期
  onMounted(() => {
    getCartList()
  })
</script>

<style lang="scss" scoped>
  .page-content {
    .cart-detail {
      .mt-4 {
        margin-top: 16px;
      }
    }

    .user-info {
      .openid {
        margin-bottom: 4px;
        font-size: 12px;
        font-weight: 500;
        color: var(--el-text-color-primary);
        word-break: break-all;
      }

      .nickname {
        font-size: 14px;
        color: var(--el-text-color-secondary);
      }
    }

    .product-info {
      .name {
        margin-bottom: 4px;
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      .type {
        font-size: 12px;
      }
    }

    .stats-info {
      .el-statistic {
        text-align: center;
      }
    }

    .empty-cart {
      padding: 40px 0;
      text-align: center;
    }
  }
</style>
